package com.company.笔试.查找数组中的数返回下标无则插入;

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param target int整型 目标值
     * @param nums int整型一维数组 排序数组
     * @return int整型
     */
    public int sort (int target, int[] nums) {
        // write code here
        int len = nums.length;
        int left = 0;
        int right = len-1;
        int i = (left+right)/2;
        while (left<right&&i>=0 &&i<=len-1 && right<=len-1&& left>=0){
            if (target<nums[i]){
                right = i-1;
                i = (int) Math.ceil((right+left)/2);
            }
            else if (target>nums[i]){
                left = i + 1;
                i = (int) Math.ceil((left+right)/2);
            }
            else return i;
        }
        return i;

    }


    public int sortNew (int target, int[] nums) {
        if (nums.length==0){
            return -1;
        }
        int len = nums.length;
        int left = 0;
        int right = len-1;
        int mid = left+(right-left)/2;
        while (left<=right){
            if (nums[mid]==target) return mid;
            else if (target < nums[mid]){
                right = mid-1;
            }else if (target > nums[mid]){
                left = mid+1;
            }
            mid = left+(right-left)/2;
        }
        return -1;


    }



    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.sort(1, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(2, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(3, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(4, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(5, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(6, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(7, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sort(8, new int[]{2, 4, 5, 6, 7}));
        System.out.println("---------------------------------------------");
        System.out.println(solution.sortNew(1, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(2, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(3, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(4, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(5, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(6, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(7, new int[]{2, 4, 5, 6, 7}));
        System.out.println(solution.sortNew(8, new int[]{2, 4, 5, 6, 7}));
    }
}